package com.bieber.democamp.sharesession.servlet;

import com.bieber.democamp.sharesession.session.Session;
import com.bieber.democamp.sharesession.session.SessionManager;
import com.bieber.democamp.sharesession.session.redis.RedisSessionManager;
import com.bieber.democamp.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by bieber on 2015/3/16.
 */
public class LoginServlet extends HttpServlet {
    private SessionManager manager = new RedisSessionManager();

    @Override
    public ServletContext getServletContext() {
        final ServletContext servletContext =  super.getServletContext();
        Class<?>[] clazz= {ServletContext.class};
        return (ServletContext) Proxy.newProxyInstance(servletContext.getClassLoader(), clazz, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("method name "+method.getName());
                return method.invoke(servletContext,args);
            }
        });
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        if(StringUtils.isEmpty(userName)||StringUtils.isEmpty(password)){
            resp.sendRedirect("/");
        }
        Session session = manager.getSession(req,true);
        session.setAttribute("userName",userName);
        Cookie cookie = new Cookie(SessionManager.SESSION_COOKIE_KEY,session.getSessionId());
        cookie.setHttpOnly(true);
        resp.addCookie(cookie);
        resp.sendRedirect("/loginStatus");
    }
}
